package cc.siyecao.fastdfs.pool;

import cc.siyecao.fastdfs.extception.FastDfsException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;

@Component
public class FdfsConnectionFactory {
    @Value("${fdfs.networkTimeout}")
    private int networkTimeout;

    @Value("${fdfs.connectTimeout}")
    private int connectTimeout;

    @Value("${fdfs.charset}")
    private Charset charset;

    @Value("${fdfs.pool.enabled}")
    private boolean poolEnabled;

    /**
     * create from InetSocketAddress
     *
     * @param socketAddress
     * @return
     * @throws IOException
     */
    public FdfsConnection create(InetSocketAddress socketAddress) throws FastDfsException {
        try {
            Socket sock = new Socket();
            sock.setReuseAddress( true );
            sock.setSoTimeout( networkTimeout * 1000 );
            sock.connect( socketAddress, connectTimeout * 1000 );
            return new FdfsConnection( sock, socketAddress, charset, poolEnabled );
        } catch (Exception e) {
            throw new FastDfsException( "connect to server " + socketAddress.getAddress().getHostAddress() + ":" + socketAddress.getPort() + " fail, emsg:" + e.getMessage() );
        }
    }
}
